package com.ooho.homework03;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by hugohoo on 16-10-10.
 */
public class FileUpload extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);

        boolean isUpload = false;

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        FileItemIterator iter;

        try {
            iter = upload.getItemIterator(req);

            try(InputStream input = iter.next().openStream();
                FileOutputStream output = new FileOutputStream("/home/hugohoo/example.doc")){

                byte buffer[] = new byte[256];
                while(input.available() > 0){
                    int len = input.read(buffer);
                    output.write(buffer, 0, len);
                }

                isUpload = true;
                System.out.println("done.");
            } finally {
                if(isUpload){
                    getServletContext().getRequestDispatcher("/homework03/success.jsp").forward(req, resp);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}
